/**
 * @(#)InterceptInfoController.java 2016年4月20日
 * Copyright(C) 2015 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.ReturnJsonCode;
import org.jsbd.boss.domian.InterceptInfo;
import org.jsbd.boss.service.IInterceptInfoService;
import org.jsbd.boss.service.impl.InterceptInfoServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 拦截短信配置
 * @author <a href="mailto:luoyaxi@zhexinit.com" >罗雅锡</a>
 * @version 1.0.0
 */
@Controller
@RequestMapping("/interceptInfo")
public class InterceptInfoController {
	
	public static final Logger LOGGER = LoggerFactory
			.getLogger(InterceptInfoController.class);
	
	@Autowired
	private IInterceptInfoService interceptInfoService;
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        return "interceptInfo/list";
    }
	
	@RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        return "interceptInfo/add";
    }
	
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable String id, Model model){
        InterceptInfo form = new InterceptInfo();
        form.setId(Integer.valueOf(id));
        
        InterceptInfo intercept  = interceptInfoService.findInterceptInfo(form);
        
        model.addAttribute("interceptInfo", intercept);
        return "interceptInfo/update";
    }
	
	/**
	 * 
	 * findInterceptInfoPageList:返回拦截短信配置列表
	 * @author <a href="mailto:luoyaxi@zhexinit.com" >罗雅锡</a>
	 * @param page
	 * @param form
	 * @param request
	 * @return
	 */
    @RequestMapping(value = "/list", params = "json")
    @ResponseBody
    public Map<String, Object> findInterceptInfoPageList(DataGridModel page, InterceptInfo form, HttpServletRequest request) {
        Map<String, Object> map = interceptInfoService.findInterceptInfoPageList(page, form);
        List<InterceptInfo> interceptInfoList = (List<InterceptInfo>) map.get("rows");
        map.put("rows", interceptInfoList);
        return map;
    }
	
    /**
     * 
     * saveIntercept:保存拦截短信配置
     * @author <a href="mailto:luoyaxi@zhexinit.com" >罗雅锡</a>
     * @param form
     * @param response
     */
    @RequestMapping(value="/save",method=RequestMethod.POST)
    @ResponseBody
    public void saveIntercept(InterceptInfo form,HttpServletResponse response){
    	InterceptInfo i = interceptInfoService.findIfInterceptExist(form);
      if(i != null){
      	JSONObject resultJson = new JSONObject();
          resultJson.put(ReturnJsonCode.RETURN_CODE, 2);
          resultJson.put(ReturnJsonCode.RETURN_MSG, "包含相同的拦截号码和拦截内容的记录已存在！");
          ResponseUtils.renderJson(response, resultJson.toString());
          return ;
      }
      
      int row =interceptInfoService.saveIntercept(form);
      
      if(row>0){
        ResponseUtils.responseSuccess(response);
      }else {
        ResponseUtils.responseFailure(response);
      }
      
      
    }
    
    /**
     * 
     * update:编辑拦截短信配置
     * @author <a href="mailto:luoyaxi@zhexinit.com" >罗雅锡</a>
     * @param id
     * @param form
     * @param response
     */
    @RequestMapping(value="/{id}/update",method=RequestMethod.POST)
    @ResponseBody
    public void update(@PathVariable Integer id,InterceptInfo form,HttpServletResponse response){ 
	  	//判断修改的是不是拦截号码或者拦截内容,如果只是修改正则或者下行或者备注，则不用判断记录是否已经存在的情况
	  	if(!((StringUtils.isNotBlank(form.getMsgContent()) && StringUtils.isNotBlank(form.getOldMsgContent()) 
	  				&& form.getMsgContent().equals(form.getOldMsgContent())) 
	  					&& (StringUtils.isNotBlank(form.getPhoneNum()) 
	  							&& StringUtils.isNotBlank(form.getOldPhoneNum()) 
	  								&& form.getPhoneNum().equals(form.getOldPhoneNum())))){
	  		InterceptInfo i = interceptInfoService.findIfInterceptExist(form);
		    if(i != null){
		    	JSONObject resultJson = new JSONObject();
		        resultJson.put(ReturnJsonCode.RETURN_CODE, 2);
		        resultJson.put(ReturnJsonCode.RETURN_MSG, "包含相同的拦截号码和拦截内容的记录已存在！");
		        ResponseUtils.renderJson(response, resultJson.toString());
		        return ;
		    }
	  	}
	    int row = interceptInfoService.modifyIntercept(form);
	    if (row>0) {
	      ResponseUtils.responseSuccess(response);
	    }else {
	      ResponseUtils.responseFailure(response);
	    }  	    
    }
    
    /**
     * 拦截配置下拉框
     * 
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "/content", method = RequestMethod.GET)
    public void findInterceptList(HttpServletRequest request, HttpServletResponse response, Model model) {
      String msgContent = request.getParameter("q");
      String defaultValues = request.getParameter("defaultValues");
      
      List<Integer> ls = new ArrayList<Integer>();
      
      if (defaultValues !=null && defaultValues.length()>0) {
        String[] idsStrings = defaultValues.replaceAll(" ", "").split(",");
        for (String string : idsStrings) {
          ls.add(Integer.valueOf(string));
        }
      }

      StringBuffer jsonData = new StringBuffer("[");
      try {
    	  InterceptInfo form = new InterceptInfo();
        form.setMsgContent(msgContent);
        List<InterceptInfo> list = interceptInfoService.findInterceptInfoList(form);
        if (list != null && list.size() > 0) {
          for (InterceptInfo intercept : list) {
            jsonData.append("{");
            jsonData.append("\"id\":\"" + intercept.getId() + "\",");
            if (ls!=null && ls.size()>0) {
              for (Integer id : ls) {
                if (intercept.getId().equals(id)) {
                  jsonData.append("\"selected\":\"" + true + "\",");
                }
              }
            }
            if(intercept.getRegexContent()!= null){
            	jsonData.append("\"regexContent\":\"" + intercept.getRegexContent().replaceAll("\\\\", "\\\\\\\\") + "\",");
            }else{
          	  jsonData.append("\"regexContent\":\"" + " " + "\",");
            }
            if (msgContent!=null && msgContent.length()>0) {
              if (intercept.getMsgContent().contains(msgContent)) {
                jsonData.append("\"selected\":\"" + true + "\",");
              }
            }
            
              
            jsonData.append("\"msgContent\":\"" + intercept.getMsgContent()+"_"+intercept.getPhoneNum() + "\"},");
          }
          jsonData.delete(jsonData.toString().length() - 1, jsonData.toString().length());
        }
      } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
      }
      jsonData.append("]");
      ResponseUtils.renderJson(response, jsonData.toString());
    }

    
}
